﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using DAL;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using System.IO;
using NPOI.HSSF.Util;
using Facade.Excel;

namespace PeisongWeb.admin
{
    public partial class companySupplyRange : adminPage
    {
        protected int companyId
        {
            get
            {
                int tmp;
                try { tmp = Convert.ToInt32(ViewState["companyId"]); }
                catch { tmp = 0; }
                return tmp;
            }
            set
            { ViewState["companyId"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("FC", 1))
                {
                    if (Request.QueryString["company"] != null)
                    {
                        if (Library.Number.IsIntPositive(Request.QueryString["company"]))
                        {
                            companyId = Convert.ToInt32(Request.QueryString["company"]);
                            span_Company.InnerHtml = logic.company.getById(companyId).Company;
                            btn_Add.OnClientClick = "window.location.href='companySupplyRangeEdit.aspx?company=" + companyId + "'";
                        }
                        else
                        {
                            Library.Script.ClientUrl("companyList.aspx");
                            return;
                        }
                    }
                    else
                    {
                        Library.Script.ClientUrl("companyList.aspx");
                        return;
                    }

                    sellerBusinessNatureBind();
                    rptBind();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }
            }
        }

        private void sellerBusinessNatureBind()
        {
            DataTable dt=logic.company.getCompanyBusinessNature(companyId);

            DataView dv = new DataView(dt);
            dv.RowFilter = "isChecked=1";

            ddlProductBus.DataSource = dv;
            ddlProductBus.DataBind();
            ddlProductBus.Items.Insert(0,new ListItem("-所有等级-",""));
        }

        void rptBind()
        {
            StringBuilder where = new StringBuilder();
            where.Append("companyId="+companyId);
            if (txt_ProductNo.Value.Trim() != "")
                where.AppendFormat(" and [productNo] like '%{0}%'", txt_ProductNo.Value.Trim());
            if (!string.IsNullOrEmpty(ddlProductBus.SelectedValue))
                where.AppendFormat(" and businessNature='{0}'",ddlProductBus.SelectedValue);
            if (txt_Name.Value.Trim() != "")
                where.AppendFormat(" and [productName] like '%{0}%'", txt_Name.Value.Trim());
            if (chx_isCancel.Checked)
                where.Append(" and [isCancel] = 1");

            DataSet ds = logic.sellerRange.select(where.ToString(), "inputDt DESC,productId,businessNature", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_list.DataSource = ds.Tables[1];
            rpt_list.DataBind();
        }

        protected void rpt_list_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Del")
            {
                int srId = Convert.ToInt32(e.CommandArgument);
                string infor;
                logic.sellerRange.delete(srId,logic.sysAdmin.AdminID);
                rptBind();
                infor = "删除成功！";
                Library.Script.ClientMsg(infor);
            }
            else if (e.CommandName == "GO")
            {
                int srId = Convert.ToInt32(e.CommandArgument);
                SellerRangeEntity sr = new SellerRangeEntity();
                sr.SrId = srId;
                sr.IsCancel = false;
                int adminId = logic.sysAdmin.AdminID;
                sr.AdminId = adminId;
                logic.sellerRange.updateCancel(sr);
                rptBind();
                Library.Script.ClientMsg("继续供应成功！");
            }
            else if (e.CommandName == "CancelRange")
            {
                int srId = Convert.ToInt32(e.CommandArgument);
                SellerRangeEntity sr = new SellerRangeEntity();
                sr.SrId = srId;
                sr.IsCancel = true;
                int adminId = logic.sysAdmin.AdminID;
                sr.AdminId = adminId;
                logic.sellerRange.updateCancel(sr);
                rptBind();
                Library.Script.ClientMsg("取消成功！");
            }
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }

        protected void lbtn_Search_Click(object sender, EventArgs e)
        {
            rptBind();
        }

        protected void link_Export_SellerRange_Click(object sender,EventArgs e)
        {
            DataSet ds = logic.sellerRange.exportBySellerId(companyId);
            string companyName=logic.company.getById(companyId).Company;
            string title = string.Format("{0}供应范围【{1}】", companyName, DateTime.Now.ToShortDateString());

            if (ds.Tables.Count > 1)
            {
                DataTable tb1 = ds.Tables[0];
                Dictionary<string, string> sheets = new Dictionary<string, string>();
                for (int i = 0; i < tb1.Rows.Count; i++)
                {
                    sheets.Add(tb1.Rows[i][0].ToString(), tb1.Rows[i][1].ToString());
                }
                DataTable tb2 = ds.Tables[1];

                Dictionary<string, string> columns = new Dictionary<string, string>();
                columns.Add("productNo", "商品编号");
                columns.Add("businessNatureName", "所属级别");
                columns.Add("productName", "商品名称");
                columns.Add("unit", "单位");
                columns.Add("standard", "规格");

                ExportFacade exportHelper = new ExportFacade();
                exportHelper.ExportByWeb("categoryId={0}", sheets, columns, tb2, title, title + ".xls", null, title);
            }
        }

        // 删除选择项
        protected void btnDelSelected_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(hdSelectedSrIds.Value))
            {
                logic.sellerRange.deleteBySelected(hdSelectedSrIds.Value, companyId, logic.sysAdmin.AdminID);
                rptBind();

                Library.Script.ClientMsg("删除成功.");
            }
        }

        /// <summary>
        /// 一健初始化商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btn_zation_Click(object sender, EventArgs e)
        {
            logic.sellerRange.sellerRangeBypricebusinessNature(companyId);
          
            Coolite.Ext.Web.Ext.Msg.Alert("一健初始化商品", "一健初始化商品成功");

            rptBind();
        }
    }
}
